package com.dayu.gulimall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dayu.common.constant.ProductConstant;
import com.dayu.common.to.es.SkuEsModel;
import com.dayu.common.utils.R;
import com.dayu.gulimall.config.ElasticSearchConfig;
import com.dayu.gulimall.constant.EsConstant;
import com.dayu.gulimall.feign.ProductFeignService;
import com.dayu.gulimall.service.MallSearchService;
import com.dayu.gulimall.vo.AttrRespVo;
import com.dayu.gulimall.vo.SearchParam;
import com.dayu.gulimall.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2020/12/30 21:17
 * @description
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam searchParam) {
        //构件DSL语句
        //准备检索请求,构件检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        SearchResult searchResult = null;
        try {
            //执行检索请求
            SearchResponse response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
//            分析响应数据，封装成需要的结果
            searchResult = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return searchResult;
    }

    /**
     * 构件结果数据
     *
     * @param response
     * @param searchParam
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();

        //1、返回所有查询到的商品
        SearchHits hits = response.getHits();
        SearchHit[] productHits = hits.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (productHits != null && productHits.length > 0) {
            for (SearchHit productHit : productHits) {
                SkuEsModel esModel = JSON.parseObject(productHit.getSourceAsString(), SkuEsModel.class);
                //获取高亮的部分
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = productHit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                esModels.add(esModel);
            }
        }
        searchResult.setProducts(esModels);

        //2、当前所有商品涉及到的所有属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attr_id_agg.getBuckets();
        if (!CollectionUtils.isEmpty(attrIdAggBuckets)) {
            for (Terms.Bucket bucket : attrIdAggBuckets) {
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                Long attrId = Long.valueOf(bucket.getKeyAsString());
                ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
                String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
                ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");

                List<? extends Terms.Bucket> attrValueAggBuckets = attr_value_agg.getBuckets();
                List<String> attrValues = new ArrayList<>();
                if (!CollectionUtils.isEmpty(attrValueAggBuckets)) {
                    for (Terms.Bucket attrValueAggBucket : attrValueAggBuckets) {
                        String attrValue = attrValueAggBucket.getKeyAsString();
                        attrValues.add(attrValue);
                    }
                }
                String attrValue = attrValueAggBuckets.get(0).getKeyAsString();
                attrVo.setAttrId(attrId);
                attrVo.setAttrName(attrName);
                attrVo.setAttrValue(attrValues);
                attrVos.add(attrVo);
            }
        }
        searchResult.setAttrs(attrVos);

        //3、当前所有商品涉及到品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brand_aggBuckets = brand_agg.getBuckets();
        if (!CollectionUtils.isEmpty(brand_aggBuckets)) {
            List<SearchResult.BrandVo> brandVos1 = brand_aggBuckets.stream().map(item -> {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                Long brandId = Long.valueOf(item.getKeyAsString());
                ParsedStringTerms brand_img_agg = item.getAggregations().get("brand_img_agg");
                String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
                ParsedStringTerms brand_name_agg = item.getAggregations().get("brand_name_agg");
                String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandId(brandId);
                brandVo.setBrandImg(brandImg);
                brandVo.setBrandName(brandName);
                return brandVo;
            }).collect(Collectors.toList());
            searchResult.setBrands(brandVos1);
        }

        //4、当前所有商品涉及到的分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        if (!CollectionUtils.isEmpty(buckets)) {
            for (Terms.Bucket bucket : buckets) {
                Long catalogId = Long.valueOf(bucket.getKeyAsString());
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
                catalogVo.setCatalogId(catalogId);
                catalogVo.setCatalogName(catalogName);
                catalogVos.add(catalogVo);
            }
        }
        searchResult.setCatalogs(catalogVos);

        //5、设置分页信息
        //5.1 设置总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        //5.2 设置总页数--计算得到
        Integer pagesize = EsConstant.PRODUCT_PAGESIZE;
        int totalPages = total % pagesize == 0 ? (int) total / pagesize : (int) (total / pagesize + 1);
        searchResult.setTotalPages(totalPages);
        //5.3 设置当前页
        searchResult.setPageNum(searchParam.getPageNum());


        //面包屑导航
//        List<SearchResult.NavVo> navVos=new ArrayList<>();
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null) {
            List<SearchResult.NavVo> navVoList = attrs.stream().map(attr -> {
                String[] s = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();

                R r = productFeignService.info(Long.valueOf(s[0]));
                if (r.getCode() == 0) {
                    AttrRespVo attrRespVo = r.getData("attr", new TypeReference<AttrRespVo>() {
                    });
                    navVo.setNavName(attrRespVo.getAttrName());
                    navVo.setNavValue(s[1]);
                } else {
                    navVo.setNavName(s[0]);
                }

                String queryString = searchParam.get_queryString();
                attr = URLEncoder.encode(attr);
                attr.replace("+","%2");

                String replace = queryString.replace("&attrs="+attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?"+replace);
                return navVo;

            }).collect(Collectors.toList());
            searchResult.setNavVos(navVoList);
        }


        return searchResult;
    }

    /**
     * 准备检索请求
     * #模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存)，排序，分页，高亮，聚合分析
     *
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 1、构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1、1 must模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        //1.2 bool-filter 按照三级分类id查询
        //过滤（按照属性，分类，品牌，价格区间，库存)
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        //1.2 bool-filter 按照品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        //1.2 bool-filter 按照指定的属性查询
        List<String> attrs = param.getAttrs();
        if (!CollectionUtils.isEmpty(attrs)) {
            //attrs=1_1.5寸:8寸&2_16G:8G

            for (String attrStr : attrs) {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValus = s[1].split(":");
                boolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValus));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", boolQueryBuilder, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //1.2 bool-filter 按照是否有库存查询
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termsQuery("hasStock", param.getHasStock() == 1));
        }

        //1.2 bool-filter 按照价格区间查询
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
//            skuPrice=500_, 500_600,_600
            String skuPrice = param.getSkuPrice();
            String[] prices = skuPrice.split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (prices.length == 2) {
                rangeQuery.gte(prices[0]).lte(prices[1]);
            } else {
                if (skuPrice.endsWith("_")) {
                    rangeQuery.gte(prices[0]);
                } else {
                    rangeQuery.lte(prices[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        //把前面的所有条件都拿来封装起来
        sourceBuilder.query(boolQuery);

        //2 排序、分页、高亮
        //2.1 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            //sort =hotScore_asc/desc
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        //2.2 分页
        // pageNum:1 from :0 size:5 查询的结果就是[1,2,3,4,5]
        // from =(pageNum-1)*pageSize
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle");
        highlightBuilder.preTags("<b style='color:red'>");
        highlightBuilder.postTags("</b>");
        sourceBuilder.highlighter(highlightBuilder);

        /**
         * 聚合分析
         */
        // 1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);

        // 1.1品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        //2. 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //3. 属性聚合
        NestedAggregationBuilder nested_attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前attr_id对应的所有可能的属性值attrVaLue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));
        nested_attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(nested_attr_agg);

        String dsl = sourceBuilder.toString();
        System.out.println("查询到dsl： " + dsl);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}
